object AnonymousFunctionsDemo extends App {
  // 1. 成绩数据
  case class StudentScore(name: String, id: String, scores: Map[String, Double])

  val studentScores = List(
    StudentScore("王五", "S2825001", Map("数学" -> 85.0, "语文" -> 90.0, "英语" -> 88.0)),
    StudentScore("李四", "S2825002", Map("数学" -> 92.0, "语文" -> 82.0, "英语" -> 95.0)),
    StudentScore("张三", "S2825003", Map("数学" -> 76.0, "语文" -> 86.0, "英语" -> 80.0)),
    StudentScore("赵六", "S2825004", Map("数学" -> 68.0, "语文" -> 72.0, "英语" -> 75.0))
  )

  // 2. 高阶函数：使用函数参数处理成绩
  def analyzeScores(scores: List[StudentScore], analyzer: StudentScore => Double): List[(String, Double)] = {
    scores.map(student => (student.name, analyzer(student)))
  }

  // 3. 使用匿名函数作为分析器
  // 计算总分（匿名函数完整形式）
  val totalScoreAnalyzer: StudentScore => Double = (student: StudentScore) => {
    student.scores.values.sum
  }

  // 计算平均分（简化的匿名函数）
  val averageScoreAnalyzer = (student: StudentScore) => {
    student.scores.values.sum / student.scores.size
  }

  // 计算数学成绩与平均分的偏差（更简洁的形式）
  val mathDeviationAnalyzer = (student: StudentScore) => {
    val mathScore = student.scores.getOrElse("数学", 0.0)
    val avg = averageScoreAnalyzer(student)
    mathScore - avg
  }

  // 4. 执行分析
  println("=== 总分分析 ===")
  val totalScores = analyzeScores(studentScores, totalScoreAnalyzer)
  totalScores.foreach { case (name, score) =>
    println(s"$name: $score")
  }

  println("\n=== 平均分析 ===")
  val averageScores = analyzeScores(studentScores, averageScoreAnalyzer)
  averageScores.foreach { case (name, score) =>
    println(f"$name: $score%.1f")
  }

  // 5. 直接在调用处定义匿名函数
  println("\n=== 语文成绩分析 ===")
  val chineseScores = analyzeScores(studentScores, s => s.scores.getOrElse("语文", 0.0))
  chineseScores.foreach { case (name, score) =>
    println(s"$name: $score")
  }

  // 6. 复杂条件筛选
  println("\n=== 优秀学生筛选（平均分 >= 85）===")
  val excellentStudents = studentScores.filter { s =>
    val avg = s.scores.values.sum / s.scores.size
    avg >= 85
  }.map(_.name)
  println(s"优秀学生: ${excellentStudents.mkString(", ")}")
}
//10.1106【动手练习1】：实现学生成绩快速分析功能